//
//  SXPuserViewModels.swift
//  weibo
//
//  Created by shixinPeng on 16/2/27.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import AFNetworking


/// 用于界面的模型
class SXPuserViewModels: NSObject {
    
    //设置用户界面模型单例属性
    static let shareInstance = SXPuserViewModels()
    
    //定义一个用户模型
    var userModel:SXPUserModel?{
        
        return SXPUserModel.readUserDate()
    }
    
    /// 令牌
    var access_token: String?{
        return userModel?.access_token
    }
    
    /// 是否允许登陆
    var isLogin: Bool {

        return userModel?.access_token != nil
    }
    
    ///  从写构造方法
    override init() {

///  利用类方法返回数据
        
        
    }
    

    func loadToken(code:String, successClosure: ()->Void,failClosure: ()->Void) {
        
        //发送请求
        /*
        HTTP请求方式
        
        POST
        请求参数
        必选 	类型及范围 	说明
        client_id 	true 	string 	申请应用时分配的AppKey。
        client_secret 	true 	string 	申请应用时分配的AppSecret。
        grant_type 	true 	string 	请求的类型，填写authorization_code
        
        
        grant_type为authorization_code时
        
        必选 	类型及范围 	说明
        code 	true 	string 	调用authorize获得的code值。
        redirect_uri 	true 	string 	回调地址，需需与注册应用里的回调地址一
        */
        
        //1.实例化一个管理者
        let manger = AFHTTPSessionManager()
        
        //添加接受类型
        manger.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //2.设置参数
        let params = ["client_id":APP_KEY,
            "client_secret":APP_SECRET,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":APP_URL
        ]
        //print(params)
        
        //3.发送POST请求
        
        //let PostUrlStr = NSURL(string: "https://api.weibo.com/oauth2/access_token")!
        
        manger .POST("https://api.weibo.com/oauth2/access_token", parameters: params, progress: nil, success: { (_, JSON) -> Void in
            
            //print(JSON)
            /*
            Optional({
            "access_token" = "2.00dz11gC0hDkYL6b5e70b729vssGOE";
            "expires_in" = 157679999;
            "remind_in" = 157679999;
            uid = 2457719037;
            })
            */
            //获取到参数进行字典转模型
            if let obj = JSON as? [String: NSObject]{
                //转换
                let userModel = SXPUserModel(dict: obj)
                
                //根据模型去获取用户数据
                self.loadUserInfo(userModel, successClosure: successClosure, failClosure: failClosure)
                
            }
            
            }) { (_, error) -> Void in
                print(error)
                failClosure()
        }
    }
    
    
    func loadUserInfo(userModel: SXPUserModel, successClosure: ()->Void,failClosure: ()->Void) {

        /*
        请求参数
        必选 	类型及范围 	说明
        access_token 	true 	string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
        uid 	false 	int64 	需要查询的用户ID。
        screen_name 	false 	string 	需要查询的用户昵称。
        
        */
        let afn = AFHTTPSessionManager()
        
        //设置参数
        let perems = ["access_token": userModel.access_token ?? "",
            "uid": userModel.uid ?? ""
        ]
        
        
        //发送请求//"https://api.weibo.com/2/users/show.json"
        afn.GET("https://api.weibo.com/2/users/show.json", parameters: perems, progress: nil, success: { (_, JSON) -> Void in
            
            //print(JSON)//所需要的数据:"profile_image_url","screen_name"
            //获取数据]
            if let dict = JSON as? [String: NSObject] {
                
                userModel.screen_name = dict["screen_name"] as? String
                userModel.profile_image_url = dict["profile_image_url"] as? String
                
                //归档
                userModel.save(APP_DOCNAME)
                
                successClosure()
                
            }
            
            
            }) { (_, error) -> Void in
                
                print(error)
                failClosure()
        }
        
        
    }

}
/*//第一次请求的url
<NSMutableURLRequest: 0x7f9bab7ae260> { URL: https://api.weibo.com/oauth2/authorize?client_id=170819901&redirect_uri=http://www.taobao.com&response_type=code }

2016-02-27 09:19:32.976 weibo[21390:860664] void SendDelegateMessage(NSInvocation *): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
<NSMutableURLRequest: 0x7f9bad879b30> { URL: https://api.weibo.com/oauth2/authorize }

2016-02-27 09:20:36.090 weibo[21390:860664] void SendDelegateMessage(NSInvocation *): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
<NSMutableURLRequest: 0x7f9bad84e770> { URL: https://api.weibo.com/oauth2/authorize# }

2016-02-27 09:20:59.542 weibo[21390:860664] void SendDelegateMessage(NSInvocation *): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
<NSMutableURLRequest: 0x7f9bad906c70> { URL: https://api.weibo.com/oauth2/authorize }
<NSMutableURLRequest: 0x7f9badaa7e20> { URL: http://www.taobao.com/?code=8165c04e8c24cc67dc69504f729a06eb }
<NSMutableURLRequest: 0x7f9bab67a050> { URL: http://m.taobao.com/?sprefer=sypc00&code=8165c04e8c24cc67dc69504f729a06eb }
<NSMutableURLRequest: 0x7f9badb5c960> { URL: https://m.taobao.com/?sprefer=sypc00&code=8165c04e8c24cc67dc69504f729a06eb }
*/
/*

Optional("https://api.weibo.com/oauth2/authorize?client_id=170819901&redirect_uri=http://www.taobao.com&response_type=code")
Optional("https://api.weibo.com/oauth2/authorize")
2016-02-27 09:25:50.030 weibo[21517:864825] void SendDelegateMessage(NSInvocation *): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
Optional("https://api.weibo.com/oauth2/authorize#")
Optional("https://api.weibo.com/oauth2/authorize")
Optional("http://www.taobao.com/?code=115c62f21040502a747cc6e21b0387c9")
Optional("http://m.taobao.com/?sprefer=sypc00&code=115c62f21040502a747cc6e21b0387c9")
Optional("https://m.taobao.com/?sprefer=sypc00&code=115c62f21040502a747cc6e21b0387c9")
Optional("about:blank")

*/
